package com.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.action.InstrumentAction;
import com.bean.InstrumentBean;
import com.exception.DBException;
import com.exception.InstrumentException;
import com.util.HandleInfo;
import com.util.Regex;
import com.util.StateInfo;

public class InstrumentAddServlet extends HttpServlet
{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		String barcode = request.getParameter("barcode");
		String name = request.getParameter("name");
		String price = request.getParameter("price");
		String remark = request.getParameter("remark");
		if(null==barcode || null == name || null==price || null==remark)
		{
			HandleInfo.handle(request, response,  
					StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		if(barcode.length()>45 || name.length()>100 || price.length()>10)
		{
			HandleInfo.handle(request, response,  
					StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		
		if ("".equals(barcode) || "".equals(name))
		{
			HandleInfo.handle(request, response,  
					StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		if(!Regex.checkBarcode(barcode) || !Regex.checkInsName(name))
		{
			HandleInfo.handle(request, response,  
					StateInfo.INNER_CONFIRM_FAIL);
			return;
		} 
		if(!"".equals(price) && !Regex.checkprice(price))
		{
			HandleInfo.handle(request, response,  
					StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		
		InstrumentBean insBean = new InstrumentBean();
		insBean.setBarcode(barcode);
		insBean.setName(name);
		insBean.setPrice(price);
		insBean.setRemark(remark);
		
		try
		{
			new InstrumentAction().addInstrument(request, response, insBean);
		}
		catch (DBException e)
		{
			HandleInfo.handle(request, response,  
					e.getMessage());
			return;
		}
		catch (InstrumentException e)
		{
			HandleInfo.handle(request, response,  
					e.getMessage());
			return;
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		doGet(request, response);
	}

}
